package com.chenjun.common.exception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.chenjun.common.websocket.WebsocketEndPoint;

/**
 * 异常处理，此处用于处理不可捕获异常
 */
public class MasterExceptionHandler implements HandlerExceptionResolver {
	private static final Logger LOGGER = Logger.getLogger(MasterExceptionHandler.class);

	
	@Autowired
	@Qualifier("exceptionHandle4WebSocket")
	private RuntimeExceptionHandle4WebSocket exceptionHandle4WebSocket;
	
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("ex", ex);
		exceptionHandle4WebSocket.printSend(ex);
		if (ex instanceof org.apache.shiro.authz.UnauthenticatedException || ex instanceof org.apache.shiro.authz.UnauthorizedException) {
			String path = request.getServletPath() == null ? "" : request.getServletPath();
			if (path.endsWith(".html")) {
				return new ModelAndView("redirect:/unauthorizedException.html");
			} else {
				return new ModelAndView("forward:/unauthorizedException");
			}
		} else {
			//TODO...  
			LOGGER.error(ex, ex);
		}

		// 根据不同错误转向不同页面
		return new ModelAndView("redirect:/500.html", model);
	}
	
}
